import 'package:dio/dio.dart';
import '../../../common/extentsion/localStorageExample.dart';
import '../../../common/http/global.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class Api {
  Dio dio = Dio();

  Future<bool> sendCode<T>(Map<String, dynamic> params,
      [bool showLoading = true]) async {
    try {
      showLoadingIfNeeded(showLoading);
      const url = '$baseUrl/login/sendCode';
      var respond = await Dio().post(url, queryParameters: params);
      dismissLoadingIfNeeded(showLoading);
      var msg = '';
      if (respond.data['data'] is Map) {
        msg = "验证码发送成功";
      } else {
        msg = respond.data['data'];
      }
      EasyLoading.showToast(msg);
      return msg == "验证码发送成功" ? true : false;
    } catch (e) {
      dismissLoadingIfNeeded(showLoading);
      print('Error occurred during sendCode: $e');
      rethrow;
    }
  }

  Future<bool> login<T>(Map<String, dynamic> params,
      [bool showLoading = true]) async {
    try {
      showLoadingIfNeeded(showLoading);
      const url = '$baseUrl/login/login';
      var respond = await Dio().post(url, queryParameters: params);
      dismissLoadingIfNeeded(showLoading);
      var msg = respond.data['data'] is Map ? "登录成功" : respond.data['data'];
      EasyLoading.showToast(msg);
      await LocalStorageExample.saveBoolean("login", true);
      await LocalStorageExample.saveString(
          "token", msg == "登录成功" ? respond.data['data']['data']['token'] : '');
      return msg == "登录成功" ? true : false;
    } catch (e) {
      dismissLoadingIfNeeded(showLoading);
      print('Error occurred during sendCode: $e');
      rethrow;
    }
  }
}
